package com.jucai.pppeiyouclient.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.adapter.FilterAdapter;
import com.jucai.pppeiyouclient.adapter.OrderListAdapter;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.bean.OrderBean;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.TextCheckUtils;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.weidget.pulltorefresh.PullToRefreshForRecyclerView;
import com.jucai.pppeiyouclient.weidget.pulltorefresh.PullToRefreshLayout;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class GetOrderListActivity extends BaseActivity implements PullToRefreshLayout.OnRefreshListener {

    private static final String TAG = "OrderListActivity : ";
    private Context context;
    private Activity activity;
    private static final int SELECT_CITY = 1001;
    private static final int DO_SCREEN = 1002;
    private PullToRefreshForRecyclerView orderRv;
    private PullToRefreshLayout refreshLayout;
    private List<OrderBean> orders = new ArrayList<>();
    private OrderListAdapter orderListAdapter;
    private String sexBack, ageBack, ageBack2, timeBack, eduBack;
    private Handler mHandler = new Handler();
    private int page = 1;
    private String city_id;
    private String keyword;

    private LinearLayout lltPeiyouCity, lltPeiyouFilter, lltPeiyouSort;
    private TextView tvPeiyouCity;
    private PopupWindow filterPopupWindow, sortPopupWindow;

    private LinearLayout lltSkillContainer;//技能列表
    private TextView tvSkillHint;

    public static final int INTENT_REQUEST_SKILL = 1003;
    private List<FilterAdapter.FilterBean> selectedFilterSkill;
    private List<String> educationIdList;
    private List<FilterAdapter.FilterBean> sortList, sexList, ageList, educationList;
    private String keyWord = "";
    private String cityId;
    private boolean isSortFilter = false;
    private boolean isFilter = false;
    private boolean isPullRefresh = false;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_get_order);
        activity = this;
        context = this;

        sexBack = "";
        ageBack = "";
        timeBack = "";
        eduBack = "";
        keyword = "";
        orderListAdapter = new OrderListAdapter(GetOrderListActivity.this, orders);
        ((TextView) findViewById(R.id.common_title_text)).setText("接单");

        refreshLayout = ((PullToRefreshLayout) findViewById(R.id.refresh_view));
        orderRv = (PullToRefreshForRecyclerView) findViewById(R.id.content_view);
        orderRv.setLayoutManager(new LinearLayoutManager(GetOrderListActivity.this, LinearLayoutManager.VERTICAL, false));
        orderRv.setItemAnimator(new DefaultItemAnimator());
        orderRv.setAdapter(orderListAdapter);

        lltPeiyouCity = (LinearLayout) this.findViewById(R.id.llt_escort_city);
        lltPeiyouFilter = (LinearLayout) this.findViewById(R.id.llt_escort_filter);
        lltPeiyouSort = (LinearLayout) this.findViewById(R.id.llt_escort_sort);
        tvPeiyouCity = (TextView) this.findViewById(R.id.tv_escort_city);

        lltPeiyouFilter.setOnClickListener(this);
        lltPeiyouSort.setOnClickListener(this);

    }

    @Override
    protected void initData() {

        if (TextCheckUtils.isEmpty(SharedPreferencesUtil.getStringPreference(GetOrderListActivity.this, "PREFERENCE", "service_city", ""))) {
            tvPeiyouCity.setVisibility(View.GONE);
        } else {
            tvPeiyouCity.setVisibility(View.VISIBLE);
        }

        city_id = SharedPreferencesUtil.getStringPreference(GetOrderListActivity.this, "PREFERENCE", "service_city_id", "");
        tvPeiyouCity.setText(SharedPreferencesUtil.getStringPreference(GetOrderListActivity.this, "PREFERENCE", "service_city", ""));

        loadData();
    }

    @Override
    protected void loadNetData() {
    }

    public void loadData() {
        HashMap<String, String> orderParam = new HashMap<>();
        orderParam.put("service", "Conductor_Order.getlist");
        orderParam.put("page", page+"");

        orderParam.put("token", LoginUtils.getToken(activity));
        orderParam.put("member_id", LoginUtils.getMember_id(activity));

        if (!TextUtils.isEmpty(sexBack)) {
            orderParam.put("sex", sexBack);
        }

        if (!TextUtils.isEmpty(ageBack)) {
            orderParam.put("minage", ageBack);
        }
        if (!TextUtils.isEmpty(ageBack2)) {
            orderParam.put("maxage", ageBack2);
        }

        if (!TextUtils.isEmpty(timeBack)) {
            orderParam.put("start_time", timeBack);
        }

        if (!TextUtils.isEmpty(eduBack)) {
            orderParam.put("education", eduBack);
        }

        if (!TextUtils.isEmpty(city_id)) {
            orderParam.put("city", city_id);
        }

        if (!TextUtils.isEmpty(keyword)) {
            orderParam.put("keyword", keyword);
        }

        if (selectedFilterSkill != null && !selectedFilterSkill.isEmpty())
            orderParam.put("skill_id", selectedFilterSkill.get(0).valueName);

        LogUtils.e(TAG + "   ---> sexBack = " + sexBack + "  --> ageBack = " + ageBack + " --> eduBack = " + eduBack + "  --> PAR = " + orderParam.toString());

        CommonRequestNetData.getJsonStringDataByEncrpt(GetOrderListActivity.this, orderParam, new CommonRequestNetData.ResultCallBack() {
            @Override
            public void parseJsonString(String str) throws Exception {

                LogUtils.e(TAG + "jsonArray = " + str);
                List<OrderBean> list = new Gson().fromJson(str, new TypeToken<List<OrderBean>>() {
                }.getType());
                if (page == 1 || isFilter)
                    orders.clear();

                if (list != null && !list.isEmpty()) {
                    orders.addAll(list);
                } else
                    ToastUtils.showToast("没有更多数据~");
                orderListAdapter.setData(orders);

            }

            @Override
            public void onError(String str) throws Exception {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SELECT_CITY:
                    String cityBack = data.getStringExtra("city_name");
                    city_id = data.getStringExtra("city_id");
                    if (cityBack.length() > 4) {
                        cityBack = cityBack.substring(0, 4) + "...";
                    }
                    tvPeiyouCity.setText(cityBack);
                    break;

                case DO_SCREEN:

                    sexBack = data.getStringExtra("filter_sex");
                    ageBack = data.getStringExtra("filter_age");
                    timeBack = data.getStringExtra("filter_time");
                    eduBack = data.getStringExtra("filter_edu");

                    LogUtils.d("Order 筛选条件：" + sexBack + "|" + ageBack + "|" + timeBack + "|" + eduBack);
                    loadData();
                    break;
                case INTENT_REQUEST_SKILL:
                    if (data != null) {
                        String skillId = data.getStringExtra("skill_id");
                        String skillName = data.getStringExtra("skill_name");
                        if (!TextUtils.isEmpty(skillId) && !TextUtils.isEmpty(skillName)) {
                            FilterAdapter.FilterBean bean = new FilterAdapter.FilterBean(0, skillName, skillId, "");
                            if (selectedFilterSkill == null)
                                selectedFilterSkill = new ArrayList<>();
                            else
                                selectedFilterSkill.clear();

                            selectedFilterSkill.add(bean);
                            showPeiyouFilter(lltPeiyouFilter);
                        }
                    }
                    break;
            }
        }
    }

    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);
        tvPeiyouCity.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(GetOrderListActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;

            case R.id.llt_escort_filter:
                showPeiyouFilter(view);
                break;

            case R.id.llt_escort_sort:
                searchKeyword(view);
                break;
        }
    }

    @Override
    public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
        page =1;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadData();
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            }
        }, 500);
    }

    @Override
    public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
        ++page;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                HashMap<String, String> orderParam = new HashMap<>();
                orderParam.put("service", "Conductor_Order.getlist");
                orderParam.put("page", page + "");

                if (!TextUtils.isEmpty(sexBack)) {
                    orderParam.put("sex", sexBack);
                }

                if (!TextUtils.isEmpty(ageBack)) {
                    orderParam.put("minage", ageBack);
                }

                if (!TextUtils.isEmpty(ageBack2)) {
                    orderParam.put("maxage", ageBack);
                }

                if (!TextUtils.isEmpty(timeBack)) {
                    orderParam.put("start_time", timeBack);
                }

                if (!TextUtils.isEmpty(eduBack)) {
                    orderParam.put("education", eduBack);
                }

                if (!TextUtils.isEmpty(city_id)) {
                    orderParam.put("city", city_id);
                }

                if (!TextUtils.isEmpty(keyword)) {
                    orderParam.put("keyword", keyword);
                }

                if (selectedFilterSkill != null && !selectedFilterSkill.isEmpty())
                    orderParam.put("skill_id", selectedFilterSkill.get(0).valueName);

                CommonRequestNetData.getJsonArrayData(GetOrderListActivity.this, orderParam, true, new CommonRequestNetData.JsonArrayCallBack() {
                    @Override
                    public void parseJsonArray(JSONArray jsonArray) {
                        LogUtils.e(TAG + "jsonArray = " + jsonArray.toString());
                        List<OrderBean> list = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<OrderBean>>() {
                        }.getType());

                        if (list != null && !list.isEmpty()) {
                            orders.addAll(list);
                            orderListAdapter.setData(orders);
                        } else
                            ToastUtils.showToast("没有更多数据~");

                    }
                });
                pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            }
        }, 500);

    }

    private void showPeiyouFilter(View v) {
        final FilterAdapter sexFilterAdapter = new FilterAdapter(activity);//性别
        final FilterAdapter ageFilterAdapter = new FilterAdapter(activity);//年龄
        final FilterAdapter educationFilterAdapter = new FilterAdapter(activity);//教育
        if (filterPopupWindow == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.view_filter, null);
            MeasureHeightGirdView mhgSex = (MeasureHeightGirdView) view.findViewById(R.id.mhg_grid_view_sex);
            MeasureHeightGirdView mhgAge = (MeasureHeightGirdView) view.findViewById(R.id.mhg_grid_view_age);
            MeasureHeightGirdView mhgEducation = (MeasureHeightGirdView) view.findViewById(R.id.mhg_grid_view_education);

            View sort = view.findViewById(R.id.llt_sort);
            sort.setVisibility(View.GONE);

            LinearLayout lltSkill = (LinearLayout) view.findViewById(R.id.llt_skill);
            lltSkillContainer = (LinearLayout) view.findViewById(R.id.llt_skill_container);
            lltSkill.setVisibility(View.VISIBLE);
            tvSkillHint = (TextView) view.findViewById(R.id.include_skill);
            tvSkillHint.setText("选择技能");
            tvSkillHint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(GetOrderListActivity.this, SkillAuthenticateActivity.class);
                    i.putExtra("type", 1);
                    startActivityForResult(i, INTENT_REQUEST_SKILL);
                    if (filterPopupWindow != null) {
                        filterPopupWindow.dismiss();
                    }
                }
            });
            TextView btnReset = (TextView) view.findViewById(R.id.btn_reset);
            TextView btnSure = (TextView) view.findViewById(R.id.btn_sure);

            btnReset.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    isFilter = false;
                    sexFilterAdapter.clearSelected();
                    ageFilterAdapter.clearSelected();
                    educationFilterAdapter.clearSelected();
                    if (selectedFilterSkill != null && selectedFilterSkill.size() > 0) {
                        selectedFilterSkill.clear();
                        if (tvSkillHint != null)
                            tvSkillHint.setVisibility(View.VISIBLE);
                        if (lltSkillContainer != null)
                            lltSkillContainer.removeAllViews();
                    }

                }
            });
            btnSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isFilter = true;
                    filterPopupWindow.dismiss();

                    sexBack = sexFilterAdapter.getSelectedBean().valueName;
                    if (!TextUtils.isEmpty(ageFilterAdapter.getSelectedBean().valueName)) {
                        String[] ageArr = ageFilterAdapter.getSelectedBean().valueName.split(",");
                        ageBack = ageArr[0];
                        ageBack2 = ageArr[1];
                    }else {
                        ageBack = "";
                        ageBack2 = "";
                    }
                    eduBack = educationFilterAdapter.getSelectedBean().valueName;
                    page = 1;
                    loadData();
                }
            });

            mhgSex.setAdapter(sexFilterAdapter);
            mhgAge.setAdapter(ageFilterAdapter);
            mhgEducation.setAdapter(educationFilterAdapter);


            filterPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            filterPopupWindow.setFocusable(true);
            filterPopupWindow.setOutsideTouchable(true);
            filterPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            filterPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {

                }
            });
        }

        if (lltSkillContainer != null && selectedFilterSkill != null && selectedFilterSkill.size() > 0) {
            lltSkillContainer.removeAllViews();
            for (FilterAdapter.FilterBean bean : selectedFilterSkill) {
                if (educationIdList == null)
                    educationIdList = new ArrayList<>();
                else
                    educationIdList.clear();

                educationIdList.add(bean.valueName);
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                TextView tag = (TextView) inflater.inflate(R.layout.include_filter_tag, lltSkillContainer, false);
                tag.setTextColor(activity.getResources().getColor(R.color.app_theme_color_one));
                tag.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra("type", 1);
                        intent.setClass(activity, SkillAuthenticateActivity.class);
                        startActivityForResult(intent, INTENT_REQUEST_SKILL);
                    }
                });
                tag.setText(bean.keyName);
                lltSkillContainer.addView(tag);
            }
            if (tvSkillHint != null)
                tvSkillHint.setVisibility(View.GONE);
        } else {
            if (tvSkillHint != null)
                tvSkillHint.setVisibility(View.VISIBLE);
            if (lltSkillContainer != null)
                lltSkillContainer.removeAllViews();
        }


        if (sexList == null) {
            sexList = new ArrayList<>();
            FilterAdapter.FilterBean bean = new FilterAdapter.FilterBean(1, "不限", "", "备注");
            FilterAdapter.FilterBean bean1 = new FilterAdapter.FilterBean(2, "男", "1", "备注");
            FilterAdapter.FilterBean bean2 = new FilterAdapter.FilterBean(3, "女", "2", "备注");
            sexList.add(bean);
            sexList.add(bean1);
            sexList.add(bean2);
            sexFilterAdapter.setList(sexList);
        }
        if (ageList == null) {
            ageList = new ArrayList<>();
            FilterAdapter.FilterBean bean = new FilterAdapter.FilterBean(1, "不限", "", "");
            FilterAdapter.FilterBean bean1 = new FilterAdapter.FilterBean(2, "25以下", "0,25", "");
            FilterAdapter.FilterBean bean2 = new FilterAdapter.FilterBean(3, "25-35", "25,35", "");
            FilterAdapter.FilterBean bean3 = new FilterAdapter.FilterBean(4, "35以上", "35,100", "");
            ageList.add(bean);
            ageList.add(bean1);
            ageList.add(bean2);
            ageList.add(bean3);
            ageFilterAdapter.setList(ageList);
        }


        if (educationList == null) {
            educationList = new ArrayList<>();
            FilterAdapter.FilterBean bean = new FilterAdapter.FilterBean(1, "不限", "0", "");
            FilterAdapter.FilterBean bean1 = new FilterAdapter.FilterBean(2, "初中", "1", "");
            FilterAdapter.FilterBean bean2 = new FilterAdapter.FilterBean(3, "高中", "2", "");
            FilterAdapter.FilterBean bean3 = new FilterAdapter.FilterBean(4, "专科", "3", "");
            FilterAdapter.FilterBean bean4 = new FilterAdapter.FilterBean(5, "本科", "4", "");
            FilterAdapter.FilterBean bean5 = new FilterAdapter.FilterBean(6, "硕士", "5", "");
            FilterAdapter.FilterBean bean6 = new FilterAdapter.FilterBean(7, "博士", "6", "");
            educationList.add(bean);
            educationList.add(bean1);
            educationList.add(bean2);
            educationList.add(bean3);
            educationList.add(bean4);
            educationList.add(bean5);
            educationList.add(bean6);
            educationFilterAdapter.setList(educationList);
        }

        filterPopupWindow.setWidth(getResources().getDisplayMetrics().widthPixels);
        filterPopupWindow.showAsDropDown(v);
    }

    public void searchKeyword(View v) {
        if (sortPopupWindow == null) {
            View view = LayoutInflater.from(activity).inflate(R.layout.view_activity_head, null);

            final EditText keywork_et = (EditText) view.findViewById(R.id.et_activity_keyword);
            TextView searchTv = (TextView) view.findViewById(R.id.tv_search);
            searchTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    keyword = keywork_et.getText().toString().trim();
                    loadData();
                    if (sortPopupWindow != null) {
                        sortPopupWindow.dismiss();
                    }
                }
            });

            sortPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            sortPopupWindow.setFocusable(true);
            sortPopupWindow.setOutsideTouchable(true);
            sortPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            sortPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {

                }
            });
        }
        sortPopupWindow.setWidth(getResources().getDisplayMetrics().widthPixels);
        sortPopupWindow.showAsDropDown(v);
    }

}
